#!/bin/bash

# 从环境变量读取服务器信息
REMOTE_DIR="/data/java/"

# 定义键值对映射
declare -A JAR_MAP=(
    ["portal"]="portal"
    ["admin"]="admin"
)

# 检查是否提供了正确的参数
if [ "$#" -ne 3 ] && [ "$1" != "all" ]; then
    echo "Usage: $0 <key> <version>"
    exit 1
fi

# 获取键值
KEY="$1"
VERSION="$2"
ENVIRONMENT="$3"


start_jar() {
    local key="$1"
    # 杀死已存在的进程
    kill_existing_process "$key"
    # 启动新的进程
    start_new_process "$key"
}

kill_existing_process() {
    local key="$1"
    local remote_jar_path="${REMOTE_DIR}drama-$key-.*-SNAPSHOT.jar"
    # 构造正则表达式
    local regex=".*$remote_jar_path.*$ENVIRONMENT.*"

    # 查找并杀死已存在的进程
    local pid=$(pgrep -f "$regex")
    if [ -n "$pid" ]; then
        kill -11 "$pid"
        echo "Killed existing process for key: $key version:$VERSION ENV:$ENVIRONMENT (PID: $pid)"
    else
        echo "No existing process found for key: $key version:$VERSION ENV:$ENVIRONMENT "
    fi
}

start_new_process() {
    local key="$1"
    local remote_jar_path="${REMOTE_DIR}drama-$key-$VERSION-SNAPSHOT.jar"
    # 启动新的进程
    nohup java -jar $remote_jar_path  --spring.profiles.active=$ENVIRONMENT > /data/java/log/$key-$ENVIRONMENT.txt 2>&1 &
    echo "Started new process for key: $key version:$VERSION ENV:$ENVIRONMENT "

}

if [ "$KEY" = "all" ]; then
    for key in "${!JAR_MAP[@]}"; do
        if ! start_jar "$key"; then
            echo "Start failed for key: $key"
        fi
    done
else
    if [[ -z "${JAR_MAP[$KEY]}" ]]; then
        echo "Error: Key '$KEY' not found in the [ portal,admin ]. version:$VERSION ENV:$ENVIRONMENT"
        exit 1
    fi

    if ! start_jar "$KEY"; then
        echo "Start failed for key: $KEY version:$VERSION ENV:$ENVIRONMENT"
        exit 1
    fi
fi
